package com.netty.tcp.nettyService;

import com.netty.tcp.redis.RedisCache;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import com.netty.tcp.nettyService.NettyServerHandler;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hzj
 * @date 2021/1/7 18:18
 * 解码器
 */
@Log4j2
public class MyDecoderHandler extends MessageToMessageDecoder<ByteBuf> {
    private final Charset charset;
    private String data = "";



    public MyDecoderHandler() {
        this(Charset.defaultCharset());
    }

    public MyDecoderHandler(Charset charset) {
        if (charset == null) {
            throw new NullPointerException("charset");
        } else {
            this.charset = charset;
        }
    }
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        String imei = msg.toString(this.charset).trim();

//        if(imei.length()==15){ //心跳发送的IMEI码
//            redisCache.setCacheObject(imei,ctx.channel().id()); //将客户端存入redis
//        }
        String HEXES = "0123456789ABCDEF";
        byte[] req = new byte[msg.readableBytes()];
        msg.readBytes(req);
        final StringBuilder hex = new StringBuilder(2 * req.length);

        for (int i = 0; i < req.length; i++) {
            byte b = req[i];
            hex.append(HEXES.charAt((b & 0xF0) >> 4))
                    .append(HEXES.charAt((b & 0x0F)));
        }
        out.add(hex.toString());
    }
//        protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
//            ByteBuf bufff = Unpooled.buffer();//netty需要用ByteBuf传输
//            bufff.writeBytes(hexString2Bytes(msg.toString(this.charset).trim()));//对接需要16进制
//            out.add(bufff);
//        }
//    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
//        String s = msg.toString(this.charset).trim();
//        Map map = checkData(s);
//        Boolean flag = (Boolean) map.get("flag");
//        if(flag){
//            String data = map.get("data").toString();
//            out.add(data);
//        }else {
//            return;
//        }
//    }

    /**
     * 对于终端收到的信息进行检验，包括：1心跳注册，2从机执行回复
     * @param msg
     * @return
     */
    private String checkMsg(String msg){
        //在此处可以加上合法性判断，对接收到的信息进行验证
        return msg;
    }

    private Map checkData(String msg){
        Map<String,Object> map = new HashMap<>();
        data = data + msg;
//        if((msg.startsWith("{") && msg.endsWith("}"))){
            map.put("data",msg);
            map.put("flag",true);
            return map;
//        }
//
//        if(data.startsWith("{") && data.endsWith("}")){
//            map.put("data",data);
//            map.put("flag",true);
//            return map;
//        }
//        map.put("flag",false);
//        return map;
    }
    public byte[] hexString2Bytes(String src) {
        int l = src.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            ret[i] = (byte) Integer.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
        }
        return ret;
    }
}
